package core.bmp.worker.filter;

import java.io.File;

import core.bmp.AbsWorker;
import core.bmp.Bmp;
import core.bmp.model.BmpData;
import core.bmp.utils.PixelUtil;

public class EqualizerFilterWorker extends AbsWorker {

	/* 继承 */

	@Override
	protected File onPrepareImageFile() {
		return Bmp.BMP_LENA;
	}

	@Override
	public void onWork(BmpData bmpData) {
		int[] argb = bmpData.getArgbPix();
		// 获取每个颜色分量的范围
		int colorCount = 0x1 << (bmpData.getColorBit() / 3);

		// 统计灰度个数
		int[] grays = statisticsGrayCount(colorCount, argb);

		// 统计灰度映射
		byte[] grayMap = statisticGrayMap(argb.length, colorCount, grays);

		int gray;
		for (int i = 0, len = argb.length; i < len; i++) {
			gray = argb[i] & 0x000000FF;
			argb[i] = PixelUtil.createGrayArgb(grayMap[gray]);
		}
	}

	/* 拓展 */

	private int[] statisticsGrayCount(int colorCount, int[] argb) {
		int[] grays = new int[colorCount];
		int gray;
		for (int i = 0, len = argb.length; i < len; i++) {
			gray = argb[i] & 0x000000FF;
			grays[gray]++;
		}
		return grays;
	}

	private byte[] statisticGrayMap(int size, int colorCount, int[] grays) {
		byte[] grayMap = new byte[colorCount];
		int lastCount = 0;
		float fSize = size;
		for (int i = 0; i < colorCount; i++) {
			lastCount += grays[i];
			float prob = lastCount / fSize;
			grayMap[i] = (byte) ((colorCount - 1) * prob + 0.5);
		}
		return grayMap;
	}

}
